package logic

import (
	"context"
	"fmt"
	"shopping-mall/models"

	"shopping-mall/shopping_rpc/internal/svc"
	"shopping-mall/shopping_rpc/shopping_rpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type FindProductLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewFindProductLogic(ctx context.Context, svcCtx *svc.ServiceContext) *FindProductLogic {
	return &FindProductLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *FindProductLogic) FindProduct(in *shopping_rpc.FindProductRequest) (*shopping_rpc.FindProductResponse, error) {
	// todo: add your logic here and delete this line
	var product struct {
		models.Product
		ClassName string
		UserName  string
	}
	if models.DB.Debug().Where("products.id = ?", in.ProductId).Model(&models.Product{}).Joins("join users on products.user_id = users.id join classes on products.class_id = classes.id").Select("products.*,classes.name as class_name,users.name as user_name").Scan(&product).Error != nil {
		return nil, fmt.Errorf("服务器繁忙")
	}
	fmt.Println(product)
	if models.DB.Exec("update products set browse_number = browse_number+1 where id = ?", in.ProductId).Error != nil {
		return nil, fmt.Errorf("服务器繁忙")
	}
	return &shopping_rpc.FindProductResponse{
		UserName:     product.UserName,
		Title:        product.Title,
		Price:        float32(product.Price),
		BrowseNumber: int64(product.BrowseNumber),
		Image:        product.Image,
		ClassName:    product.ClassName,
		CreatedAt:    product.CreatedAt.String(),
		UpdatedAt:    product.UpdatedAt.String(),
	}, nil
}
